﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Ross.EntityFramework
{
    public class Common
    {
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encryptKey"></param>
        /// <returns></returns>
        public static string Encrypt(string str, string encryptKey)
        {
            try
            {
                byte[] key = Encoding.Unicode.GetBytes(encryptKey);
                byte[] data = Encoding.Unicode.GetBytes(str);

                DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
                MemoryStream MStream = new MemoryStream();

                CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
                CStream.Write(data, 0, data.Length);
                CStream.FlushFinalBlock();
                byte[] temp = MStream.ToArray();
                CStream.Close();
                MStream.Close();

                return Convert.ToBase64String(temp);
            }
            catch
            {
                return str;
            }
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encryptKey"></param>
        /// <returns></returns>
        public static string Decrypt(string str, string encryptKey)
        {
            try
            {
                byte[] key = Encoding.Unicode.GetBytes(encryptKey);
                byte[] data = Convert.FromBase64String(str);

                DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
                MemoryStream MStream = new MemoryStream();

                CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
                CStream.Write(data, 0, data.Length);
                CStream.FlushFinalBlock();
                byte[] temp = MStream.ToArray();
                CStream.Close();
                MStream.Close();

                return Encoding.Unicode.GetString(temp);
            }
            catch
            {
                return str;
            }
        }

        public static string GetInnerException(Exception ex)
        {
            if (ex.InnerException != null)
            {                
                return GetInnerException(ex.InnerException);
            }
            return ex.Message;
        }

    }
}
